package com.gxc.core.filter;

import com.gxc.core.content.SessionContent;
import com.gxc.core.validate.code.ImageCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码校验过滤器.
 *
 * @author GongXincheng
 * @since 2019-10-17 16:47
 */
public class ValidateCodeFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    private AuthenticationFailureHandler authenticationFailureHandler;

    public ValidateCodeFilter() {
    }

    public ValidateCodeFilter(AuthenticationFailureHandler authenticationFailureHandler) {
        this.authenticationFailureHandler = authenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 判断请求路径并时候post请求
        if (StringUtils.equals(request.getRequestURI(), "/authentication/form") && "post".equalsIgnoreCase(request.getMethod())) {
            try {
                checkValidateCode(new ServletWebRequest(request));
            } catch (ValidateCodeException e) {
                logger.error(getClass().getName() + ": {}", e.getMessage());
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 校验验证码逻辑.
     */
    private void checkValidateCode(ServletWebRequest servletWebRequest) {
        String imageCode = servletWebRequest.getParameter("imageCode");
        ImageCode imageCodeObject = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, SessionContent.VALIDATE_SESSION_KEY);

        if (StringUtils.isBlank(imageCode)) {
            throw new ValidateCodeException("验证码不能为空");
        } else if (imageCodeObject == null) {
            throw new ValidateCodeException("验证码生成异常");
        } else if (imageCodeObject.isExpried()) {
            sessionStrategy.removeAttribute(servletWebRequest, SessionContent.VALIDATE_SESSION_KEY);
            throw new ValidateCodeException("验证码已过期");
        } else if (!imageCodeObject.getCode().equalsIgnoreCase(imageCode)) {
            throw new ValidateCodeException("验证码错误");
        }
        sessionStrategy.removeAttribute(servletWebRequest, SessionContent.VALIDATE_SESSION_KEY);
    }
}
